package com.xmim.server.serialization;


import com.xmim.fulcrum.FulcrumCodec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;


/**
 * User:cool coding
 * Date:2018/1/7
 * Time:21:33
 * 编码
 */
@Slf4j
public class ProtobufEncoder extends MessageToByteEncoder {
    private final FulcrumCodec fulcrumCodec;

    public ProtobufEncoder(FulcrumCodec fulcrumCodec) {
        this.fulcrumCodec = fulcrumCodec;
    }


    @Override
    protected void encode(ChannelHandlerContext ctx, Object in, ByteBuf out) {
        try {
            byte[] data = fulcrumCodec.encode(in);
            int length = data.length;
            out.writeInt(length);
            out.writeBytes(data);
        } catch (Exception e) {
            log.debug("编译数据异常", e);
        }
    }

    @Override
    public boolean isSharable() {
        return super.isSharable();
    }
}
